package com.ice.delay.task.core.helper;

import com.alibaba.fastjson.JSON;
import com.ice.delay.task.core.constant.ServerErrorCode;
import com.ice.framework.common.base.ResponseResult;
import com.ice.framework.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * HttpServlet 工具类
 * @author wangwei
 * @Date 2021/12/20 15:06
 */
public class RequestHelper {

    private static Logger logger = LoggerFactory.getLogger(RequestHelper.class);

    /**
     * 获取 HttpServletRequest 实例
     * @Author wangwei
     * @Date 2021/12/20
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getRequest();
    }

    /**
     * 获取 HttpServletResponse实例
     * @return
     * @Author wangwei
     * @Date 2021/12/20
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getResponse();
    }


    /**
     * 获取 HttpSession实例
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 判断请求是否是异步请求
     * @return
     */
    public static boolean isAjaxRequest() {
        HttpServletRequest request = getRequest();
        if (((request.getHeader("accept") != null && request.getHeader("accept").contains("application/json")) ||
                (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断请求是否直接由地址栏发出
     * @return
     */
    public static boolean isRefererRequest() {
        HttpServletRequest request = getRequest();

        //地址栏的为GET请求
        if (request.getMethod().equals("POST")) {
            return false;
        }

        //地址栏请求时,Referer为空
        if (request.getHeader("Referer") == null) {
            return true;
        }

        return false;
    }

    /**
     * 判断浏览器的类型(IE/non IE)
     * @return
     */
    public static boolean isIEbrowser() {
        HttpServletRequest request = getRequest();

        String userAgent = request.getHeader("user-agent");

        System.out.println("userAgent===" + userAgent);

        //IE 判断
        if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
            return true;
        }
        //Mozilla(火狐,chrome...)
        return false;
    }

    /**
     * 获取客户端IP
     *
     * @return
     */
    public static String getClientIP() {
        return getClientIP(getRequest());
    }


    /**
     * 获取客户端IP
     *
     * @return
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PX-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

    /**
     *
     * 获取请求头信息中的 Authorization
     *
     * @author liaohongjian
     * @since 2017年7月15日
     * @return
     */
    public static String getAuthorization() {
        return getAuthorization(getRequest());
    }

    /**
     *
     * 获取请求头信息中的 Authorization
     *
     * @author liaohongjian
     * @since 2017年7月15日
     * @return
     */
    public static String getAuthorization(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if ("undefined".equalsIgnoreCase(authorization)) {
            authorization = null;
        }
        if (authorization == null) {
            authorization = request.getParameter("token");
        }
        return authorization;
    }


    /**
     * 获取请求token参数
     *
     * @see #getAuthorization()
     *
     * @author liaohongjian
     * @since 2017年7月15日
     * @return
     */
    public static String getAccessToken() {
        return getAuthorization();
    }

    /**
     * 获取请求服务
     *
     * @author liaohongjian
     * @since 2017年7月17日
     * @return
     */
    public static String getRequestURL(HttpServletRequest request) {
        return request.getRequestURL().toString();
    }

    /**
     * 获取请求服务
     *
     * @author liaohongjian
     * @since 2017年7月17日
     * @return
     */
    public static String getRequestURL() {
        return getRequestURL(getRequest());
    }


    /**
     * 输出ResponseResult响应结果
     *
     * <p> 默认按 ;
     *
     * @author liaohongjian
     * @since 2017年7月18日
     * @param result
     */
    public static void write(ResponseResult<Object> result) {
        write(getResponse(), result);
    }


    /**
     * 输出ResponseResult响应结果
     *
     * <p> 默认按 ;
     *
     * @author liaohongjian
     * @since 2017年7月18日
     * @param result
     */
    public static void write(HttpServletResponse response, ResponseResult<Object> result) {
        response.reset();
        //处理跨域问题
        response.setHeader("Access-Control-Allow-Origin", getRequest().getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,token,X-Requested-With");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }
    }

    /**
     * 将异常信息通过ResponseResult输出响应结果
     *
     * <p> 默认按 ;
     *
     * @author liaohongjian
     * @since 2017年7月18日
     */
    public static void write(Exception e) {
        write(getResponse(), e);
    }

    /**
     * 将异常信息通过ResponseResult输出响应结果
     *
     * <p> 默认按 ;
     *
     * @author liaohongjian
     * @since 2017年7月18日
     */
    public static void write(HttpServletResponse response, Exception e) {
        logger.error("系统异常", e);
        String errorCode = ServerErrorCode.ERROR.getCode();
        String message = ServerErrorCode.ERROR.getMessage();

        if (e instanceof BusinessException) {
            errorCode = ((BusinessException) e).getCode();
            message = ((BusinessException) e).getMessage();
        }

        ResponseResult<Object> result = new ResponseResult<Object>(errorCode, message);
        result.setRequestId(UUID.randomUUID().toString());

        write(response, result);
    }
}
